﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MeTalker.Aide.Forms;
using MeTalker.Aide.Mode;
using MeTalker.Aide.data;
using Top.Api.Response;
using System.Threading;
using MeTalker.SDK.Core;
using MeTalker.Window.SDK.Core;
using System.Drawing;

namespace MeTalker.Aide
{
    internal class CheckPieces : ServiceBase,IWorkMode
    {
        public IWork Work { get; set; }
        int period;
        TaobaoHelper taobaoHelper;
        Timer mTimer;
        Timer mTimerClose;
        DateTime baseDateTime;
        IDictionary<string, int> dicts;
        internal CheckPieces(ProcInfo proc, int period, IWork work)
        {
            dicts = new Dictionary<string, int>();
            this.period = period;
            WorkProcess = proc;
            Work = work;
            baseDateTime = DateTime.Now;
            base.Init(proc);
        }
        void ShowOrder(string msg, int count)
        {
            if (!string.IsNullOrEmpty(msg) && count > 0)
                new frmQueryOrder(msg, count).ShowOrder();
        }

        void CloseCallback(object sender)
        {
            try
            {
                IntPtr hwndMain = WindowControl.FindWindow(null, "系统提示");
                int pid;
                WindowControl.GetWindowThreadProcessId(hwndMain, out pid);
                if (pid == WorkProcess.Pid)
                {
                 int d =   WindowControl.EnumChildWindows(hwndMain, FindhWndCloseAlter, 0);
                 Console.WriteLine(d);
                }
                if (!DataFactory.SystemConfig.IsHiddenPlatform)
                {
                    if (!WindowControl.IsWindowVisible(this.hwndMain))
                    {
                        //StopGuide();
                        if (WorkCallback != null)
                        {
                            WorkCallback.BeginInvoke(this, null, MeTalker.Aide.Forms.TalkerState.Closed, null, null);
                        }
                    }
                }
            }
            catch { }
        }

        string OLD_MSG = "";
        void Handler(IntPtr hWnd)
        {
            try
            {
                string text = GetText(hWnd);
                lock (this)
                {
                    if (!string.IsNullOrEmpty(text))
                    {
                        if (text.Equals(OLD_MSG))
                        {
                            return;
                        }
                        OLD_MSG = text;
                        string[] msgs = text.Replace(" ", "").Split(new char[] { '\r', '\n' });
                        int len = msgs.Length;
                        string msg_name = msgs[len - 3];
                        string msg = msgs[len - 1];
                        string SendName = msg_name.Substring(0, msg_name.IndexOf("("));
                        string ReceivTime = msg_name.Replace(SendName, "").Replace("(", "").Replace(")", "");
                        ReceivTime = ReceivTime.Substring(0, ReceivTime.Length - 1);
                        if (!WorkProcess.Alias.Equals(SendName) && !"系统消息".Equals(SendName))
                        {
                            SendText(mainhWndContent, DataFactory.SystemConfig.AutoQuerySalutation);
                            msg = taobaoHelper.FindOrderTrack(SendName);
                            Console.WriteLine("返回" + msg);
                            if (!string.IsNullOrEmpty(msg))
                            {
                                msg = DataFactory.SystemConfig.LetterTip + Environment.NewLine + msg;
                                SendText(mainhWndContent, msg);
                            }
                            else
                            {
                                SendText(mainhWndContent, DataFactory.SystemConfig.NotQuerySalutation);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                if (UtilHelper.DEBUG)
                    MuchInfo.Logs.MILog.Error("自动查件", ex);
            }
            finally {
                CloseSession();
            }
        }
        Random random = new Random(100);
        Point basepoint;
        Point currpoint = new Point();
        int currCount = 0;
        bool initPoint = false;

        #region 继承
      
        void TimerCallback(object sender)
        {
            try
            {
                lock (this)
                {
                    if (WindowControl.IsWindowEnabled(buttonHandle))
                    {
                        WindowControl.EnumChildWindows(hwndMain, FindhWndCloseAlter, 0);
                        Handler(mainhWndResposneContent);
                    }
                    else
                    {
                        //WindowControl.GetCursorPos(ref currpoint);
                        //if (!initPoint)
                        //{
                        //    initPoint = true;
                        //    basepoint = currpoint;
                        //}
                        //else
                        //{
                        //    if (basepoint.X == currpoint.X && basepoint.Y == currpoint.Y)
                        //    {
                        //        currCount++;
                        //    }
                        //    else
                        //    {
                        //        basepoint = currpoint;
                        //    }
                        //}
                        //if (currCount > UtilHelper.MAX_COUNT)
                        //{
                        //    currCount = 0;
                        //    MouseControl.SetCursorPos(random.Next(), random.Next());
                        //}
                    }
                }
                if (DataFactory.SystemConfig.IsHiddenPlatform)
                {
                    if (WindowControl.IsWindowVisible(this.hwndMain))
                    {
                        WindowControl.ShowWindow(hwndMain, WindowControl.SW_HIDE);
                    }
                }
                else
                {
                    if (WindowControl.IsIconic(hwndMain))
                    {
                        WindowControl.ShowWindowAsync(hwndMain, WindowControl.SW_RESTORE);
                    }

                    if (!WindowControl.IsWindowVisible(this.hwndMain))
                    {
                        if (WorkCallback != null)
                        {
                            WorkCallback.BeginInvoke(this, null, MeTalker.Aide.Forms.TalkerState.Closed, null, null);
                        }
                    }
                }
            }
            catch
            {
            }
        }

        public TalkerState WorkMode { get { return TalkerState.AutoQueryPieces; } }

        void IWork.Refresh() { }

        public WorkModeCallBack WorkCallback { get; set; }

        public ProcInfo WorkProcess { get; set; }

        void IWorkMode.InitView()
        {

        }

        void IWorkMode.InitData()
        {

        }

        bool IWork.Start()
        {
            try
            {
                if (DataFactory.Accounts != null)
                {
                    var ds = from temp in DataFactory.Accounts where temp.AccountId.Equals(WorkProcess.Alias) select temp;
                    Account account = ds.FirstOrDefault();
                    if (account != null)
                    {
                        taobaoHelper = new TaobaoHelper(account);
                    }
                    else
                    {
                        ds = from temp in DataFactory.Accounts where temp.Default select temp;
                        account = ds.FirstOrDefault();
                        if (account != null)
                        {
                            taobaoHelper = new TaobaoHelper(account);
                        }
                    }
                    if (taobaoHelper != null)
                    {
                        Handler(mainhWndResposneContent);
                        mTimer = new Timer(TimerCallback, null, 100, 100);
                    }
                    else
                    {
                        new frmTip("错误: 无法找到店铺数字证书！自动查件需要店铺数字证书, 请在系统设置增加有效数字证书。").Show();
                        if (WorkCallback != null)
                        {
                            WorkCallback.BeginInvoke(this, null, MeTalker.Aide.Forms.TalkerState.Closed, null, null);
                        }
                        ((IWork)this).Stop();
                    }
                }
                    if (UtilHelper.DEBUG)
                        MuchInfo.Logs.MILog.Info(string.Format("{0}启动自动查件模式", WorkProcess.Alias));
                    Console.WriteLine(WorkProcess.Alias + "启动自动查件模式");
                return true;
            }
            catch
            {
                return false;
            }
            finally {
                Thread.Sleep(1000);
                CloseSession();
            }
        }

        void IWork.Stop()
        {
            try
            {
                if (UtilHelper.DEBUG)
                    MuchInfo.Logs.MILog.Info(string.Format("{0}退出自动查件模式", WorkProcess.Alias));
                Console.WriteLine(WorkProcess.Alias + "退出自动查件模式");
                if (mTimer != null)
                {
                    mTimer.Dispose();
                }
                if (mTimerClose != null)
                {
                    mTimerClose.Dispose();
                }
                mTimerClose = null;
                mTimer = null;
                WindowControl.ShowWindow(hwndMain, WindowControl.SW_SHOW);
            }
            catch { }
            finally {
                WindowControl.ShowWindow(hwndMain, WindowControl.SW_SHOW);
            }
        }
        #endregion
    }
}